package be.rubengerits.android.car.dashboard.pager.custom;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import be.rubengerits.android.car.dashboard.R;
import be.rubengerits.android.car.dashboard.pager.GenericListFragment;
import be.rubengerits.android.car.dashboard.pager.custom.music.MusicAdapter;

public class MusicFragment extends GenericListFragment {

	private View mItemSelected;

	public List<String> currentSongs = new ArrayList<String>(Arrays.asList(new String[]{"Song 1", "Song 2", "Song 3", "Song 4", "Song 5", "Song 6", "Song 7", "Song 8", "Song 9", "Song 10", "Song 11", "Song 12", "Song 13", "Song 14"}));

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// TODO create seperate adapter that can handle music
		setListAdapter(new MusicAdapter(getActivity(), android.R.layout.simple_list_item_1, currentSongs));
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mItemSelected = getView().findViewById(R.id.m_music_selection);

		// listeners
		SongChangeListener songChangeListener = new SongChangeListener();
		getListView().setOnItemSelectedListener(songChangeListener);
		getListView().setOnItemClickListener(songChangeListener);

		getListView().requestFocusFromTouch();
		getListView().setSelection(10);
	}

	@Override
	protected int getFragmentId() {
		return R.layout.viewpager_music;
	}

	private class SongChangeListener implements OnItemSelectedListener, OnItemClickListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			changeSelectedSong(position);
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			changeSelectedSong(position);
		}

		private void changeSelectedSong(int position) {
			if (position < 10) {
				position = 10;
			} else if (position > currentSongs.size() - 11) {
				position = currentSongs.size() - 11;
			}

			getListView().requestFocusFromTouch();
			getListView().smoothScrollToPositionFromTop(position, (int) mItemSelected.getY(), 500);
		}
	}
}
